﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Animoso.Data.Conventions;
using Animoso.Domain;
using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;

namespace Animoso.Data.Database
{
    public class Database
    {
        public FluentConfiguration GetConfiguration()
        {
            AutoPersistenceModel autoPersistenceModel = AutoMap.AssemblyOf<Section>()
                .Where(t => t.BaseType == typeof(DomainObject));
            autoPersistenceModel.Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultCascade.All());
            autoPersistenceModel.Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never());
            autoPersistenceModel.Conventions.Add<TextConvention>();
            autoPersistenceModel.Conventions.Add<AuthorConvention>();
            string connectionString = System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"];
            FluentConfiguration config = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(connectionString))
                .Mappings(m => m.AutoMappings.Add(autoPersistenceModel));

            return config;
        }

        public void CreateSchema()
        {
            FluentConfiguration config = GetConfiguration();
            SchemaExport schemaExport = new SchemaExport(config.BuildConfiguration());
            schemaExport.Drop(true, true);
            schemaExport.Create(true, true);
        }

        public void UpdateSchema()
        {
            FluentConfiguration config = GetConfiguration();
            new SchemaUpdate(config.BuildConfiguration())
                    .Execute(true, true);
        }
    }
}
